<template>
  <van-popup v-model:show="showPopup" position="right" destroy-on-close :style="{ width: '100%', height: '100%' }" teleport="body">
    <van-nav-bar title="产品详情" fixed @click-right="showPopup = false">
      <template #right>
        <van-icon name="cross" size="18" />
      </template>
    </van-nav-bar>
    <div class="detail-wrapper">
      <van-cell-group class="mb-10">
        <van-cell>
          <template #title>
            <div class="title">{{ form.productNameAlias || form.productName }}</div>
          </template>
        </van-cell>
        <van-cell title="">
          <template #label>
            <div class="trade-wrapper">
              <div class="trade-info">
                <div class="trade-info-item">
                  <div class="trade-info-label">产品代码：</div>
                  <div class="trade-info-value">{{ form.productCodeAlias || form.productCode }}</div>
                </div>
                <div class="trade-info-item">
                  <div class="trade-info-label">持有资产：</div>
                  <div class="trade-info-value bold">{{ formatAmountBySize(holdingAssets) }}{{ formatAmountTextBySize(holdingAssets) }}</div>
                </div>
                <div class="trade-info-item">
                  <div class="trade-info-label">持有成本：</div>
                  <div class="trade-info-value bold">{{ formatAmountBySize(holdingCost) }}{{ formatAmountTextBySize(holdingCost) }}</div>
                </div>
              </div>
              <div class="content-item income-loss">
                <div class="content-item-value" :class="form.symbol === '' ? '' : form.symbol === '+' ? 'income' : 'loss'">
                  <span>{{ form.symbol }}</span>
                  <span>{{ formatAmountBySize(Math.abs(form.profitLossAmount || 0)) }}</span>
                  <span class="unit">{{ formatAmountTextBySize(Math.abs(form.profitLossAmount || 0)) }}</span>
                </div>
                <div class="content-item-title">浮动盈亏</div>
              </div>
              <van-divider vertical />
              <div class="content-item net-value">
                <div class="content-item-value">
                  <span>{{ form.currentNetValue }}</span>
                </div>
                <div class="content-item-title">单位净值</div>
              </div>
            </div>
          </template>
        </van-cell>
      </van-cell-group>
      <van-cell class="mb-10 chart-block">
        <template #title>
          <div class="title">浮动盈亏</div>
          <div id="charts-info-sub" class="charts-info"></div>
        </template>
        <template #label>
          <!-- <van-tabs v-model:active="activeChartTime" @change="getProfitLossReport">
            <van-tab title="三月"></van-tab>
            <van-tab title="半年"></van-tab>
            <van-tab title="一年"></van-tab>
            <van-tab title="购买以来"></van-tab>
          </van-tabs> -->
          <div class="chart-wrapper">
            <div id="productProfitLossChart" ref="ProductProfitLossChart" class="chart"></div>
          </div>
        </template>
      </van-cell>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, computed, shallowRef, onBeforeUnmount } from 'vue'
import { apiGetSLBProfitLossReportForAdminNew, apiGetProductProfitLossReportForAdmin, apiGetSLBProfitLossReportForUser, apiGetProductProfitLossReportForUser } from '@/api/user'
import dayjs from 'dayjs'
import { deepClone, getProfitLossReportParam, formatAmountBySize, formatAmountTextBySize } from '@/utils/common'
import store from '@/stores'
import { storeToRefs } from 'pinia'
import * as echarts from 'echarts'
import { times } from '@/utils/calc'

const showPopup = ref(false)
const form = ref({})
const productType = ref(1)
const activeChartTime = ref(3) // 默认显示购买以来
const productProfitLossChart = shallowRef(null)

const { userInfo } = storeToRefs(store.user)
const userType = computed(() => {
  return userInfo.value.type
})

// 持有资产
const holdingAssets = computed(() => {
  if (productType.value === 1) {
    return userType.value === 'user' ? form.value.assets || 0 : form.value.totalAssets || 0
  } else {
    return times(form.value.holdingUnits || 0, form.value.currentNetValue)
  }
})

// 持有成本
const holdingCost = computed(() => {
  if (productType.value === 1) {
    return userType.value === 'user' ? form.value.cost || 0 : form.value.totalCost || 0
  } else {
    return form.value.productCost || 0
  }
})

const open = (product, type) => {
  form.value = deepClone(product)
  form.value.profitLossAmount = type === 1 ? (userType.value === 'user' ? product.profitLoss || 0 : product.totalProfitLoss || 0) : product.productProfitLoss || 0
  form.value.symbol = form.value.profitLossAmount === 0 ? '' : form.value.profitLossAmount > 0 ? '+' : '-'
  productType.value = type
  showPopup.value = true
  getProfitLossReport()
}

const getProfitLossReport = async () => {
  const params = getProfitLossReportParam(activeChartTime.value)
  let result
  if (productType.value === 1) {
    if (userType.value === 'user') {
      result = apiGetSLBProfitLossReportForUser(params)
    } else {
      result = apiGetSLBProfitLossReportForAdminNew(params)
    }
  } else {
    params.productId = form.value.id
    if (userType.value === 'user') {
      result = apiGetProductProfitLossReportForUser(params)
    } else {
      result = apiGetProductProfitLossReportForAdmin(params)
    }
  }

  result.then((res) => {
    initChart(res)
  })
}

function initChart(dataList) {
  if (productProfitLossChart.value) {
    productProfitLossChart.value.dispose()
  }
  const xAxisData = []
  const seriesData = []
  dataList.forEach((item) => {
    xAxisData.push(dayjs(item.transactionDate).format('YYYY-MM-DD'))
    seriesData.push(item.totalProfitLoss)
  })
  let series = {
    name: form.value.productNameAlias || form.value.productName,
    type: 'line',
    smooth: true,
    showSymbol: false,
    data: seriesData,
    markPoint: {
      data: [],
      label: {
        show: true,
        formatter: (params) => {
          return moneyFormat(params.value)
        }
      }
    }
  }
  productProfitLossChart.value = echarts.init(document.getElementById('productProfitLossChart'))
  productProfitLossChart.value.setOption({
    tooltip: {
      trigger: 'axis',
      // 让tooltip不可见
      // formatter: function() {
      //   return ''
      // },
      position: function (point, params, dom, rect, size) {
        // 完全居中计算
        const tooltipWidth = dom ? dom.offsetWidth : 0
        const x = (size.viewSize[0] - tooltipWidth) / 2
        return [x, 15]
      },
      valueFormatter: (value, dataIndex) => {
        const xAxisData = productProfitLossChart.value.getOption().xAxis[0].data
        const xValue = xAxisData[dataIndex]
        const infoDiv = document.getElementById('charts-info-sub')
        infoDiv.innerHTML = `<span>浮动盈亏 <strong style="color: ${value >= 0 ? '#ff4d4f' : '#52c41a'}">${value >= 0 ? '+' : ''}${value.toFixed(2)}</strong>（元）</span> <span>${xValue}</span>`
        return `${(value || 0).toFixed(2)}元${(userType.value === 'user' && productType.value === 1) || productType.value === 2 ? ` | 净值：${dataList[dataIndex].netValue}` : ''}`
      }
    },
    toolbox: {
      show: false
    },
    // legend: {
    //   bottom: 0
    // },
    grid: {
      top: '12%',
      left: '3%',
      right: '4%',
      bottom: '2%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        margin: 20
      },
      data: xAxisData
    },
    yAxis: {
      type: 'value',
      scale: true,
      name: '盈亏（万元）',
      nameGap: 25,
      alignTicks: true,
      boundaryGap: [0.2, 0.2],
      axisLabel: {
        formatter: (v) => {
          const intPart = String(v).split('.')
          const intArr = intPart[0].split('')
          // if (intArr.length > 8) {
          //   return String(v).substring(0, intArr.length - 8) + '亿'
          // } else 
          if (intArr.length > 4) {
            return String(v).substring(0, intArr.length - 4) // + '万'
          } else {
            return String(v).substring(0, intArr.length) // + '元'
          }
        }
      }
    },
    series
  })
}

defineExpose({
  open
})

onBeforeUnmount(() => {
  if (productProfitLossChart.value) {
    productProfitLossChart.value.dispose()
  }
})
</script>

<style lang="less" scoped>
.detail-wrapper {
  padding-top: var(--van-nav-bar-height);
  height: calc(100vh - var(--van-nav-bar-height));
  background-color: #f7f7f7;
  overflow-y: auto;
  .title {
    font-size: 16px;
    font-weight: bold;
  }
  .bold {
    font-weight: bold;
  }
  .trade-wrapper {
    display: flex;
    align-items: center;
    color: #323232;
    .trade-info {
      flex: 1;
      margin-right: 10px;
      .trade-info-item {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #323232;
        .trade-info-label {
          width: 5em;
        }
        &:not(:last-child) {
          margin-bottom: 10px;
        }
      }
    }
    .content-item {
      text-align: center;
      height: 100%;
      &.net-value {
        min-width: 55px;
      }
      &.income-loss {
        min-width: 100px;
      }

      .content-item-title {
        margin-top: 10px;
      }

      .content-item-value {
        display: flex;
        align-items: baseline;
        justify-content: center;
        font-size: 22px;
        height: 22px;
        line-height: 22px;
        font-weight: bold;

        .unit {
          font-size: 12px;
          margin-left: 2px;
        }

        &.loss {
          color: #43c07d;
        }

        &.income {
          color: #f53f3f;
        }
      }
    }
  }
  .charts-info {
    display: flex;
    justify-content: space-between;
    padding: 5px 12px 0 0;
    font-size: 12px;
  }
  .chart-block {
    .chart-wrapper {
      height: 350px;
      .chart {
        height: 100%;
        width: 100%;
      }
    }
  }
}
</style>
